package org.truenewx.tnxjee.repo.redis.prepare;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.truenewx.tnxjee.core.Strings;
import org.truenewx.tnxjee.core.util.LogUtil;
import org.truenewx.tnxjee.core.util.StringUtil;

@Component
public class RedisDataPrepareCommandParser {

    public List<RedisDataPrepareCommand> parse(Resource resource) {
        List<RedisDataPrepareCommand> commands = new ArrayList<>();
        try (InputStream in = resource.getInputStream()) {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(in);
            Element rootElement = doc.getRootElement();
            List<Element> deleteElements = rootElement.elements("delete");
            for (Element deleteElement : deleteElements) {
                RedisDataDeleteCommand command = new RedisDataDeleteCommand();

                String profileString = deleteElement.attributeValue("profiles");
                if (StringUtils.isNotBlank(profileString)) {
                    command.setProfiles(StringUtil.splitAndTrim(profileString, Strings.COMMA));
                }

                Element includesElement = deleteElement.element("includes");
                if (includesElement != null) {
                    List<String> includes = new ArrayList<>();
                    List<Element> keyElements = includesElement.elements("key");
                    for (Element keyElement : keyElements) {
                        includes.add(keyElement.getTextTrim());
                    }
                    command.setIncludes(includes);
                }

                Element excludesElement = deleteElement.element("excludes");
                if (excludesElement != null) {
                    List<String> excludes = new ArrayList<>();
                    List<Element> keyElements = excludesElement.elements("key");
                    for (Element keyElement : keyElements) {
                        excludes.add(keyElement.getTextTrim());
                    }
                    command.setExcludes(excludes);
                }

                commands.add(command);
            }
        } catch (DocumentException | IOException e) {
            LogUtil.error(getClass(), e);
        }
        return commands;
    }

}
